<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-button type="primary" @click="addRolesPopupDialozg = true"
          >添加角色</el-button
        ></el-row
      >
    </el-card>
    <!-- 角色列表区域 -->
    <el-table :data="rolesList" border stripe>
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template v-slot="scope">
          <el-row
            v-for="(item1, i1) in scope.row.children"
            :key="item1.id"
            :class="['bdbottom', 'vcenter', i1 === 0 ? 'bdtop' : '']"
          >
            <!-- 渲染一级权限 -->
            <el-col :span="5">
              <el-tag closable @close="removeRightById(scope.row, item1.id)">{{
                item1.authName
              }}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>

            <el-col :span="19">
              <el-row
                :class="['vcenter', i2 === 0 ? ' ' : ' bdtop']"
                v-for="(item2, i2) in item1.children"
                :key="item2.id"
              >
                <!-- 渲染二级和三级权限 -->
                <!-- 二级权限 -->
                <el-col :span="6">
                  <el-tag
                    type="success"
                    closable
                    @close="removeRightById(scope.row, item2.id)"
                    >{{ item2.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 三级权限 -->
                <el-col :span="18">
                  <el-tag
                    type="warning"
                    v-for="item3 in item2.children"
                    :key="item3.id"
                    closable
                    @close="removeRightById(scope.row, item3.id)"
                    >{{ item3.authName }}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- 序号列 -->
      <el-table-column type="index" label="#"></el-table-column>
      <!-- 操作列 -->
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作" width="290">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            v-model="scope.row"
            @click="editorRole(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            v-model="scope.row"
            @click="open(scope.row)"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-setting"
            v-model="scope.row"
            @click="showSetRightDialog(scope.row)"
            >分配权限</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加用户信息弹出页 -->
    <el-dialog title="添加角色" :visible.sync="addRolesPopupDialog" width="30%">
      <!-- 弹窗主体内容 -->
      <el-form ref="" label-width="80px" :model="addroles">
        <el-form-item label="角色">
          <el-input v-model="addroles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            v-model="addroles.roleDesc"
            @keyup.enter.native="Confirm()"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 弹窗页脚 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesPopupDialog = false">取 消</el-button>
        <el-button type="primary" @click="Confirm()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户弹出页 -->
    <el-dialog
      title="修改角色"
      :visible.sync="editorRolesPopupDialog"
      width="30%"
    >
      <!-- 弹窗主体内容 -->
      <el-form ref="" label-width="80px" :model="editorRoles">
        <el-form-item label="角色">
          <el-input v-model="editorRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editorRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 弹窗页脚 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editorRolesPopupDialog = false">取 消</el-button>
        <el-button type="primary" @click="Confirmeditor()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色弹窗 -->
    <el-dialog
      title="分配权限"
      :visible.sync="SetRightDialogVisible"
      width="50%"
      @close="setRightDialogClosed()"
    >
      <!-- 树形结构 -->
      <el-tree
        :data="rightlist"
        :props="RightProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="SetRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      rolesList: [],
      rightlist: [],
      // 控制修改权限弹出窗是否弹出
      SetRightDialogVisible: false,
      // 控制添加角色弹出窗是否弹出
      addRolesPopupDialog: false,
      // 控制修改角色弹出窗是否弹出
      editorRolesPopupDialog: false,
      // 添加角色的弹窗表单数据
      addroles: {
        roleName: "",
        roleDesc: "",
      },
      RightProps: {
        label: "authName",
        children: "children",
      },
      // 添加角色的弹窗表单数据
      editorRoles: {},
      // 默认勾选的节点
      defKeys: [],
      rolesId: "",
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    // 获取所有角色
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      console.log(res);
      if (res.meta.status != 200) {
        this.$message.error("人物权限列表获取失败");
      } else {
        this.rolesList = res.data;
      }
    },
    // 表单确认后执行添加方法
    async Confirm() {
      this.addRolesPopupDialog = false;
      console.log(this.addroles);
      const { data: res } = await this.$http.post("roles", this.addroles);
      if (res.meta.status != 201) {
        this.$message.error("添加用户失败");
      } else {
        this.$message.success("添加用户成功");
        this.addroles = {};
      }
      this.getRolesList();
    },

    // 编辑角色信息
    editorRole(Roleinfo) {
      this.editorRolesPopupDialog = true;
      this.editorRoles = Roleinfo;
    },
    // 编辑信息确认修改
    async Confirmeditor() {
      this.editorRolesPopupDialog = false;
      const { data: res } = await this.$http.put(
        `roles/${this.editorRoles.id}`,
        this.editorRoles
      );
      if (res.meta.status != 200) {
        this.$message.error("修改角色信息失败");
      } else {
        this.$message.success("修改角色信息成功");
        this.editorRoles = {};
      }
      this.getRolesList();
    },

    //删除角色
    async deleteRole(Roleinfo) {
      const { data: res } = await this.$http.delete(`roles/${Roleinfo.id}`);
      if (res.meta.status != 200) {
        this.$message.error("删除失败");
      } else {
        this.$message.success("删除成功");
        this.getRolesList();
      }
    },

    // 删除角色二次确认
    open(Roleinfo) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {})
        .then(() => {
          this.deleteRole(Roleinfo);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 删除角色权限
    async removeRightById(roles, rigthId) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmResult !== "confirm") {
        return this.$message.info("取消了操作");
      }
      const { data: res } = await this.$http.delete(
        `roles/${roles.id}/rights/${rigthId}`
      );
      if (res.meta.status != 200) {
        this.$message.error("修改权限失败,请重试");
      } else {
        this.$message.success("修改权限成功");
        // this.getRolesList();
        roles.children = res.data;
      }
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defKeys = [];
    },
    // 分配权限
    async showSetRightDialog(role) {
      this.rolesId = role.id;
      console.log("当前修改的ID是" + this.rolesId);
      // 获取所有权限的数据
      this.SetRightDialogVisible = true;
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status != 200) {
        this.$message.error("失败");
      } else {
        this.$message.success("成功");
        // 递归获取三级节点的id
        this.getLeafKeys(role, this.defKeys);
        this.rightlist = res.data;
      }
    },

    // 通过递归的形式获取全部三级id
    getLeafKeys(node, arr) {
      // 如果当前node不包含children属性 则代表这是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }

      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    async allotRights() {
      this.SetRightDialogVisible = false;
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      console.log(keys);
      const key = keys.join(",");
      console.log(key);
      const { data: res } = await this.$http.post(
        `roles/${this.rolesId}/rights`,
        { rids: key }
      );

      if (res.meta.status != 200) {
        this.$message.error("修改失败");
      } else {
        this.$message.success("修改成功");
        this.getRolesList();
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  margin-left: 50px;
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
</style>